/**
 * Copyright (C) 2010 Telecom Digital
 */
package cc.telecomdigital.tdstock.activity.chart;

import static cc.mango.android.chartutil.ChartCommons.DOWN_CHART_Y_LABEL_TEXTSIZE;
import static cc.mango.android.chartutil.ChartCommons.SUNFLOWER_SLEEP_TIME;
import static cc.mango.android.chartutil.ChartCommons.UP_CHART_BITMAP_TEXTSIZE;
import static cc.mango.android.chartutil.ChartCommons.UP_CHART_SMA_TEXTSIZE;
import static cc.mango.android.chartutil.ChartCommons.UP_CHART_X_LABEL_TEXTSIZE;
import static cc.mango.android.chartutil.ChartCommons.UP_CHART_Y_LABEL_TEXTSIZE;
import static cc.mango.android.chartutil.ChartCommons.scaleRatio;
import static cc.mango.android.chartutil.ChartCommons.screenWidth;
import static cc.mango.android.chartutil.ChartCommons.textSizeReviseCount;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Process;
import android.os.AsyncTask.Status;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cc.mango.android.chartdata.ChartDataHelper;
import cc.mango.android.chartdata.DownloadChartTask;
import cc.mango.android.chartview.BaseView;
import cc.mango.android.chartview.DownNoDataView;
import cc.mango.android.chartview.DownSunFlowerView;
import cc.mango.android.chartview.UpNoDataView;
import cc.mango.android.chartview.UpSunFlowerView;
import cc.mango.android.dto.StkDaily;
import cc.mango.android.dto.StkIntraday;
import cc.mango.common.FinalKey;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.Activity_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.ScreenOrientationChangeListener.IScreenOrientationChangeListener;
import cc.telecomdigital.tdstock.Framework.UniqueItem.ScreenOrientationChangeListener.SCR_ORIENTATION;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

public abstract class NvChart extends Activity_Framework implements IScreenOrientationChangeListener //LandscapeActivity
{
	/** The encapsulated graphical view. */
	protected static View			_aboveView;									//上面的图表View
	protected static View			_underView;									//下面的图表View

	protected LinearLayout			_aboveContainer;								//上面的图表View的副控件
	protected LinearLayout			_underContainer;								//下面的图表View的副控件   
	protected TextView				_stkname;

	
	protected static final String				ACTION_INSTALL_SHORTCUT			= "com.android.launcher.action.INSTALL_SHORTCUT";
	protected static final String				EXTRA_SHORTCUT_DUPLICATE			= "duplicate";
	
	protected static String					_menu_exit_app_res				= null;
	protected static String					_menu_gen_launcher_res			= null;

	private static String					SUCCESS_CODE					= "0";
	public static final int					EXIT_APP						= Menu.FIRST;
	public static final int					CREATE_LAUNCHER				= Menu.FIRST + 1;
	
	//时间类型按钮
	protected Button				_bt1day;
	protected Button				_bt1week;
	protected Button				_bt1month;
	protected Button				_bt3months;
	protected Button				_bt6months;
	protected Button				_bt1year;
	protected Button				_bt2years;

	//Line,CS,SMA,VOL,RSI按钮
	protected ImageView				_btline;
	protected ImageView				_btcandlestick;
	protected ImageView				_btsma;
	protected ImageView				_btvol;
	protected ImageView				_btrsi;

	//当前股票、外汇或者指数的代码
	protected String				theItemCode;

	//触摸时提示栏ID
	protected final int[]			LABEL_IDS			= {
			R.id.chart_label_0, R.id.chart_label_1, R.id.chart_label_2,
			R.id.chart_label_3, R.id.chart_label_4, R.id.chart_label_5 };

	//触摸时提示栏View
	protected TextView[]			_tv_labels		= new TextView[LABEL_IDS.length];

	protected String[]				_res_strings;

	protected static final int		COLOR_SKY			= 0xff0033ff;
	protected static final int		COLOR_BLUE		= 0xff000080;

	//触摸时chart中显示的价格下的背景图
	protected Bitmap				bm;											//by zhengan

	//当前是否处于触摸状态
	protected boolean				isTouching		= false;

	//触摸的数据点在整个dateList中的索引
	protected int					index			= 0;

	//当前图表的数据
	protected List					dateList;

	//存储当前时间类型
	protected String				label;

	//辅助获得图表的数据
	protected ChartDataHelper		chartDataHelper;

	protected final static String		TAG				= NvChart.class
														.getSimpleName();

	//太阳花的图片
	protected Bitmap				sunFlower;

	//触摸时chart中指示当前点的圆形图片
	protected Bitmap				circle;										//indecator point

	//太阳花动画是否停下来的标志
	protected boolean				stopFlag			= true;

	//更新上面chart的数据的异步线程
	protected DownloadUpChartTask		upTask;

	//更新chart的数据的异步线程
	protected DownloadDownChartTask	downTask;

	//同时更新上下chart的数据的异步线程
	protected DownloadAllChartTask	allTask;

	//上面chart上的太阳花
	protected UpSunFlowerView		aview;

	//下面chart上的太阳花
	protected DownSunFlowerView		dview;

	//太阳花的父控件
	protected LinearLayout			downSunFlowerContainer;
	protected LinearLayout			upSunFlowerContainer;

	//按下返回键时的提示对话框
	private AlertDialog				dialog;

	private final int				CHART_VIEW		= 1;
	private final int				SUNFLOWER_VIEW		= 2;

	//是否在同时更新上下两个chart的标志位
	private boolean				isAllTaskExcecuting	= false;

	////////////////by zhengan	

	//初始化chart中的文本信息
	protected void getRes()
	{

		int[] RES_IDS = {
				R.string.index_sharetraded, //量
				R.string.index_high, R.string.index_low,
				R.string.index_open, R.string.index_rsi,
				R.string.activity_nvchart_rsi_no_value };

		_res_strings = new String[RES_IDS.length];

		for (int index = 0; index < RES_IDS.length; index++)
		{
			_res_strings[index] = this.getResources().getString(
					RES_IDS[index]);
		}
	}

	//界面中的View
	protected void findViews()
	{

		_aboveContainer = (LinearLayout) findViewById(R.id.aboveview);
		_underContainer = (LinearLayout) findViewById(R.id.underview);
		_stkname = (TextView) findViewById(R.id.stkname);

		_bt1day = (Button) findViewById(R.id.bt1day);
		_bt1week = (Button) findViewById(R.id.bt1week);
		_bt1month = (Button) findViewById(R.id.bt1month);
		_bt3months = (Button) findViewById(R.id.bt3months);
		_bt6months = (Button) findViewById(R.id.bt6months);
		_bt1year = (Button) findViewById(R.id.bt1year);
		_bt2years = (Button) findViewById(R.id.bt2years);

		_btline = (ImageView) findViewById(R.id.btline);
		_btcandlestick = (ImageView) findViewById(R.id.btcandlestick);
		_btsma = (ImageView) findViewById(R.id.btsma);
		_btvol = (ImageView) findViewById(R.id.btvol);
		_btrsi = (ImageView) findViewById(R.id.btrsi);

		for (int index = 0; index < LABEL_IDS.length; index++)
		{
			_tv_labels[index] = (TextView) findViewById(LABEL_IDS[index]);
		}

		//太阳花的父控件
		downSunFlowerContainer = (LinearLayout) findViewById(R.id.sunflower_underview);
		upSunFlowerContainer = (LinearLayout) findViewById(R.id.sunflower_aboveview);

		//太阳花
		dview = new DownSunFlowerView(NvChart.this, sunFlower);
		aview = new UpSunFlowerView(NvChart.this, sunFlower);

		//将太阳花添加到父控件中去
		downSunFlowerContainer.addView(dview);
		upSunFlowerContainer.addView(aview);

	}

	//更新上下chart界面
	protected void initChartLayout()
	{
		initUpChartLayout();
		initDownChartLayout();

		TDStockLog.d("Print_Info", "==initChartLayout===");
	}

	//更新上下chart界面
	protected void initUpChartLayout()
	{

		if (_aboveView == null)
		{ //如果chartView为空，提示信息“暂时未有资料”

			_aboveView = new UpNoDataView(this,
					getString(R.string.activity_nvchart_no_data));

		}
		_aboveContainer.removeAllViews();
		_aboveContainer.addView(_aboveView);

		showUpView(CHART_VIEW);

	}

	//更新下chart界面
	protected void initDownChartLayout()
	{

		if (_underView == null)
		{ //如果chartView为空，提示信息“暂时未有资料”

			_underView = new DownNoDataView(this,
					getString(R.string.activity_nvchart_no_data));

		}

		_underContainer.removeAllViews();
		_underContainer.addView(_underView);

		showDownView(CHART_VIEW);
	}

	//给时间类型的按钮和图表类型按钮添加监听
	protected void setListeners()
	{

		setDateButtonListeners();

		setImageButtonListeners();
	}

	//给图表类型按钮添加监听
	protected abstract void setImageButtonListeners();

	//给时间类型的按钮添加监听
	protected void setDateButtonListeners()
	{

		Button.OnClickListener bt1DayListener = new Button.OnClickListener()
		{
			public void onClick(View v)
			{

				handleDateButtonListener(v,
						FinalKey.INTRADAY_DATETYPE_TODAY);
			}
		};

		Button.OnClickListener bt1WeekListener = new Button.OnClickListener()
		{
			public void onClick(View v)
			{

				handleDateButtonListener(v, FinalKey.INTRADAY_DATETYPE_WEEK);

			}
		};

		Button.OnClickListener bt1MonthListener = new Button.OnClickListener()
		{
			public void onClick(View v)
			{

				handleDateButtonListener(v, FinalKey.DAILY_DATETYPE_MONTH);
			}
		};

		Button.OnClickListener bt3MonthsListener = new Button.OnClickListener()
		{
			public void onClick(View v)
			{

				handleDateButtonListener(v, FinalKey.DAILY_DATETYPE_3MONTHS);

			}
		};

		Button.OnClickListener bt6MonthsListener = new Button.OnClickListener()
		{
			public void onClick(View v)
			{

				handleDateButtonListener(v, FinalKey.DAILY_DATETYPE_6MONTHS);

			}
		};

		Button.OnClickListener bt1YearListener = new Button.OnClickListener()
		{
			public void onClick(View v)
			{

				handleDateButtonListener(v, FinalKey.DAILY_DATETYPE_YEAR);
			}
		};

		Button.OnClickListener bt2YearsListener = new Button.OnClickListener()
		{
			public void onClick(View v)
			{

				handleDateButtonListener(v, FinalKey.DAILY_DATETYPE_2YEARS);

			}
		};

		_bt1day.setOnClickListener(bt1DayListener);
		_bt1week.setOnClickListener(bt1WeekListener);
		_bt1month.setOnClickListener(bt1MonthListener);
		_bt3months.setOnClickListener(bt3MonthsListener);
		_bt6months.setOnClickListener(bt6MonthsListener);
		_bt1year.setOnClickListener(bt1YearListener);
		_bt2years.setOnClickListener(bt2YearsListener);

	}

	//恢复时间类型按钮背的景色
	protected void setButtonBackgroundColor(int color)
	{
		_bt1day.setBackgroundColor(color);
		_bt1week.setBackgroundColor(color);
		_bt1month.setBackgroundColor(color);
		_bt3months.setBackgroundColor(color);
		_bt6months.setBackgroundColor(color);
		_bt1year.setBackgroundColor(color);
		_bt2years.setBackgroundColor(color);
	}

	//调整图表类型按钮在可用和不可用状态下的透明度
	protected void setImageButtonStatus(ImageView button, boolean enable)
	{
		button.setEnabled(enable);
		if (enable)
			button.setAlpha(255);
		else
			button.setAlpha(100);

	}

	//恢复所有时间类型的按钮为可用状态
	protected void setAllButtonEnabled(boolean enable)
	{
		_bt1day.setEnabled(enable);
		_bt1week.setEnabled(enable);
		_bt1month.setEnabled(enable);
		_bt3months.setEnabled(enable);
		_bt6months.setEnabled(enable);
		_bt1year.setEnabled(enable);
		_bt2years.setEnabled(enable);
	}

	//触摸时根据当前数据点的索引更新提示信息
	protected void updateTextViewByPoint(int xPos, List list)
	{
		try
		{
			if (list == null || list.isEmpty() || xPos < 0
					|| xPos >= list.size() || list.get(xPos) == null)
			{
				return;
			}

			updateTextView(_tv_labels[0], label);
			TDStockLog.d(TAG, label);

			Object data = list.get(xPos);

			if (data instanceof StkIntraday)
			{

				StkIntraday stkIntraday = (StkIntraday) data;

				updateStkIntradayInfoView(stkIntraday);

			}
			else if (data instanceof StkDaily)
			{

				StkDaily stkDaily = (StkDaily) data;

				updateStkDailyInfoView(stkDaily);

			}
		}
		catch (Exception e)
		{
			TDStockLog.d(TAG, e.getMessage() == null ? "unknown exception!" : e
					.getMessage());
			e.printStackTrace();
		}

	}

	protected void updateTextView(TextView tv, String value)
	{

		tv.setText(value == null ? CommonDefn.DEFAULT_FIELD_VALUE : value);
	}

//	@Override
//	public void onConfigurationChanged(Configuration newConfig)
//	{
//
//		TDStockLog.d("Print_Info", "nvchart onconfinu changed");
//
//		if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
//		{
//
//			forwardToLastActivity();
//
//		}
//
//		super.onConfigurationChanged(newConfig);
//	}

	/**
	 * change  buttonview and chart_lables  visibility
	 * */
	protected void changeVisibility()
	{
		View buttonView = this.findViewById(R.id.buttonview);

		View chart_lables = this.findViewById(R.id.chart_lables);

		buttonView.setVisibility(View.GONE);

		chart_lables.setVisibility(View.VISIBLE);

		TDStockLog.d("Print_Info", "changeVisible");

	}

	/**
	 * restore  buttonview and chart_lables  visibility
	 * */
	protected void restoreVisibility()
	{
		View buttonView = this.findViewById(R.id.buttonview);

		View chart_lables = this.findViewById(R.id.chart_lables);

		buttonView.setVisibility(View.VISIBLE);

		chart_lables.setVisibility(View.GONE);

		TDStockLog.d("Print_Info", "restoreVisible");
	}

	////////////by zhengan	
	//将图表的数据写入到SD卡中，用于调试
	protected void writeToFile(final List list, final String dateType)
	{

		//		if(true){
		//			
		//			return;
		//		}

		new Thread()
		{
			public void run()
			{
				super.run();

				int size = list.size();

				TDStockLog.d("Print_Info", "list.size():" + size);

				StringBuilder s = new StringBuilder();
				for (Object temp : list)
				{
					s.append(temp.toString());
				}

				String content = s.toString();
				String stockName = ((ITDLApplication) getApplicationContext())
						.getCurrentStockName();
				String name = "NvChart." + dateType;

				FileWriter fw = null;
				BufferedWriter bw = null;

				TDStockLog.d("Print_Info", "write to " + name
						+ "===============================");

				try
				{
					SimpleDateFormat df = new SimpleDateFormat(
							"yyyyMMddHHmm");
					Date date = new Date(System.currentTimeMillis());
					String time = df.format(date);
					File file = new File("/sdcard/log/" + name + time);
					//					file.createNewFile();
					File parent = file.getParentFile();
					parent.mkdirs();

					///////////////////////delete all file

					File[] allFiles = parent.listFiles();

					for (File temp : allFiles)
					{

						temp.delete();
					}

					/////////////////////////

					fw = new FileWriter(file);
					bw = new BufferedWriter(fw);

					bw.write("ItemCode:" + theItemCode);
					bw.write("\nName:" + stockName);
					bw.write("\nDateType:" + dateType);
					bw.write("\nsize:" + size);

					bw.write(content);

				}
				catch (FileNotFoundException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finally
				{
					try
					{
						bw.close();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try
					{
						fw.close();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
		}.start();

	}

	//同时刷新上下图表界面
	public void refreshView()
	{
		this.setAllImageViewVisibility(!getIsTouching());//是否隐藏goup A 和 group B

		_underView.postInvalidate();//刷新上面图表

		_aboveView.postInvalidate();//刷新下面图表

		if (getIsTouching())
		{

			this.changeVisibility();

			this.updateTextViewByPoint(index, dateList);
		}
		else
		{

			this.restoreVisibility();
		}

	}

	//处理当前时间类型按钮的状态
	private void handleButtonStatus(View v)
	{
		setAllButtonEnabled(true);

		setButtonBackgroundColor(COLOR_BLUE);

		v.setBackgroundColor(COLOR_SKY);

		v.setEnabled(false);

		label = (String) ((Button) v).getText();
	}

	//当为StkIntraday数据图表时更新提示信息
	protected void updateStkIntradayInfoView(StkIntraday stk)
	{

		String dateTime = stk.getDtyyyymmdd().substring(4, 6) + "月"
				+ stk.getDtyyyymmdd().substring(6, 8) + "日  "
				+ stk.getTime().substring(0, 2) + ":"
				+ stk.getTime().substring(2, 4);

		updateTextView(_tv_labels[1], dateTime);

		String vol = getStringVol(stk.getVol());

		updateTextView(_tv_labels[2], _res_strings[0] + vol);

		String high = getStringPrice(stk.getDayhigh());

		updateTextView(_tv_labels[3], _res_strings[1] + high);

		String low = getStringPrice(stk.getDaylow());

		updateTextView(_tv_labels[4], _res_strings[2] + low);

		String open = getStringPrice(stk.getOpen());

		updateTextView(_tv_labels[5], _res_strings[3] + open);
	}

	//当为StkIntraday数据图表时更新提示信息
	protected abstract void updateStkDailyInfoView(StkDaily stk);

	//将double vol转换为文本的vol
	protected String getStringVol(double vol)
	{

		int k = 1000;
		int m = 1000000;
		int b = 1000000000;
		//		  double t = 1000000000000;

		long l = 0;
		if (vol / k >= b)
		{

			l = Math.round(vol / b / k);
			return l + "T";
		}
		else if (vol >= b)
		{
			l = Math.round(vol / b);
			return l + "B";
		}
		else if (vol >= m)
		{
			l = Math.round(vol / m);
			return l + "M";
		}
		else if (vol >= k)
		{
			l = Math.round(vol / k);
			return l + "K";
		}
		else
		{
			l = Math.round(vol);
			return l + "";
		}

	}

	//设置当前时间类型
	protected abstract void setDateType(String dateType);

	//获取当前时间类型
	public abstract String getDateType();

	//处理当前图表类型按钮的状态
	protected abstract void handleImageButtonStatus();

	//处理时间类型按钮的点击事件
	private void handleDateButtonListener(View v, String dateType)
	{

		handleButtonStatus(v); //处理按钮状态

		setDateType(dateType); //设置当前时间类型

		handleImageButtonStatus();//handle image status 

		drawChart(dateType); //绘制图表

		TDStockLog.d("listen", "=========on click");

	}

	//绘制上下两个图表
	protected void drawChart(String dateType)
	{

		//先尝试取消之前的所有更新数据的异步任务
		if (allTask != null && allTask.getStatus() != Status.FINISHED)
		{

			allTask.cancel(true);

			boolean b = allTask.isCancelled();

			TDStockLog.d("Print_Info", "====allTask is cancell=======" + b);
		}

		if (upTask != null && upTask.getStatus() != Status.FINISHED)
		{

			upTask.cancel(true);

			boolean b = upTask.isCancelled();

			TDStockLog.d("Print_Info", "====upTask is cancell=======" + b);
		}

		if (downTask != null && downTask.getStatus() != Status.FINISHED)
		{

			downTask.cancel(true);

			boolean b = downTask.isCancelled();

			TDStockLog.d("Print_Info", "====downTask is cancel=====" + b);
		}

		//新建一个异步任务
		allTask = new DownloadAllChartTask();

		//执行异步任务
		allTask.execute(dateType);

	}

	//绘制上面图表
	protected void drawAboveChart(final String datetype)
	{
		//先尝试取消之前的更新上面chart数据的异步任务
		if (upTask != null && upTask.getStatus() != Status.FINISHED)
		{

			upTask.cancel(true);

			boolean b = upTask.isCancelled();

			TDStockLog.d("Print_Info", "====upTask iscancell=======" + b);
		}

		upTask = new DownloadUpChartTask();

		upTask.execute(datetype);
	}

	//绘制下面图表
	protected void drawDownChart(final String datetype)
	{
		//先尝试取消之前的更新下面chart数据的异步任务
		if (downTask != null && downTask.getStatus() != Status.FINISHED)
		{

			downTask.cancel(true);

			boolean b = downTask.isCancelled();

			TDStockLog.d("Print_Info", "====downTask is cancel=====" + b);
		}

		downTask = new DownloadDownChartTask();

		downTask.execute(datetype);

	}

	//改变图表类型按钮状态
	protected abstract void changeAllImageButtonStatus();

	//设置触摸时当前数据点在图表dataList中的索引
	public void setIndex(int index)
	{

		this.index = index;

	}

	//获取触摸时当前数据点在图表dataList中的索引
	public int getIndex()
	{

		return index;
	}

	//获取当前是否处于触摸状态
	public boolean getIsTouching()
	{
		return isTouching;
	}

	//设置当前是否处于触摸状态
	public void setIsTouching(boolean isTouching)
	{
		this.isTouching = isTouching;
	}

	//by zhengan
	//启动时根据上次的时间类型更新界面
	protected void initView(String dateType)
	{

		if (FinalKey.INTRADAY_DATETYPE_TODAY.equals(dateType))
		{

			_bt1day.performClick();
		}
		else if (FinalKey.INTRADAY_DATETYPE_WEEK.equals(dateType))
		{

			_bt1week.performClick();
		}
		else if (FinalKey.DAILY_DATETYPE_MONTH.equals(dateType))
		{

			_bt1month.performClick();
		}
		else if (FinalKey.DAILY_DATETYPE_3MONTHS.equals(dateType))
		{

			_bt3months.performClick();
		}
		else if (FinalKey.DAILY_DATETYPE_6MONTHS.equals(dateType))
		{

			_bt6months.performClick();
		}
		else if (FinalKey.DAILY_DATETYPE_YEAR.equals(dateType))
		{

			_bt1year.performClick();
		}
		else
		{

			_bt2years.performClick();
		}

	}

	//调整字体大小
	protected void reviseChartTextSize()
	{

		Display _display = this.getWindowManager().getDefaultDisplay();

		_display = ((WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();

		if (textSizeReviseCount == 0)
		{

			if (_display.getWidth() <= 320 && _display.getHeight() <= 240)
			{
				scaleRatio = 1.0f
						* /*_display.getWidth() / screenWidth */_display
								.getWidth() / _display.getHeight()
						* 0.4f; //modified by haibo, 2011-06-24, to adapt to small screen
			}
			else
			{
				scaleRatio = 1.0f * _display.getWidth() / screenWidth;
			}

			UP_CHART_BITMAP_TEXTSIZE *= scaleRatio;

			UP_CHART_X_LABEL_TEXTSIZE *= scaleRatio;

			UP_CHART_Y_LABEL_TEXTSIZE *= scaleRatio;

			DOWN_CHART_Y_LABEL_TEXTSIZE *= scaleRatio;

			UP_CHART_SMA_TEXTSIZE *= scaleRatio;

			textSizeReviseCount++;
		}

		TDStockLog.d("Print_Info", "width : height   " + _display.getWidth() + ":"
				+ _display.getHeight());

		TDStockLog.d("Print_Info", "UP_CHART_BITMAP_TEXTSIZE:"
				+ UP_CHART_BITMAP_TEXTSIZE);

		TDStockLog.d("Print_Info", "UP_CHART_X_LABEL_TEXTSIZE:"
				+ UP_CHART_X_LABEL_TEXTSIZE);

	}

	//显示是否隐藏图表类型按钮，触摸时需要隐藏所有图表类型按钮
	protected void setAllImageViewVisibility(boolean isVisible)
	{

		if (isVisible)
		{
			_btline.setVisibility(View.VISIBLE);
			_btcandlestick.setVisibility(View.VISIBLE);
			_btsma.setVisibility(View.VISIBLE);
			_btvol.setVisibility(View.VISIBLE);
			_btrsi.setVisibility(View.VISIBLE);

		}
		else
		{

			_btline.setVisibility(View.INVISIBLE);
			_btcandlestick.setVisibility(View.INVISIBLE);
			_btsma.setVisibility(View.INVISIBLE);
			_btvol.setVisibility(View.INVISIBLE);
			_btrsi.setVisibility(View.INVISIBLE);
		}

		TDStockLog.d("Print_Info", "" + isVisible);
	}

	//获得chart价格背景图片
	public Bitmap getBm()
	{
		// TODO Auto-generated method stub
		return bm;
	}

	public Bitmap getCircleBm()
	{
		// TODO Auto-generated method stub
		return circle;
	}

	//得到上面的chartView
	protected abstract View getUpView(List datalist, String dateType);

	//得到下面的chartView
	protected abstract View getDownView(List datalist, String datetype);

	/*
	 * 启动太阳花动画
	 * @param upView 上面的太阳花动画
	 * @param downView 下面的太阳花动画
	 */
	protected void startSunFlowerAnimation(final BaseView upView,
			final BaseView downView)
	{

		Thread sunFlowerThread = new Thread()
		{

			public void run()
			{
				super.run();

				TDStockLog.d("Print_Info", "=========sunflower====");

				TDStockLog.d("Print_Info", "=========sunflower start====");

				if (upView != null && downView == null)
				{

					while (!stopFlag)
					{

						upView.refresh();

						try
						{
							Thread.sleep(SUNFLOWER_SLEEP_TIME);
						}
						catch (InterruptedException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				}
				else if (downView != null && upView == null)
				{

					while (!stopFlag)
					{

						downView.refresh();

						try
						{
							Thread.sleep(SUNFLOWER_SLEEP_TIME);
						}
						catch (InterruptedException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				else if (downView != null && upView != null)
				{

					while (!stopFlag)
					{

						upView.refresh();

						downView.refresh();

						try
						{
							Thread.sleep(SUNFLOWER_SLEEP_TIME);
						}
						catch (InterruptedException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

				TDStockLog.d("Print_Info", "=========sunflower stop====");

				stopFlag = true;

			}
		};

		sunFlowerThread.setName("SunFlowerThread");

		if (stopFlag)
		{

			stopFlag = false;

			sunFlowerThread.start();
		}

	}

	//太阳花动画
	protected void stopSunFlowerAnimation()
	{

		stopFlag = true;

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO Auto-generated method stub
		/*switch (keyCode)
		{

			case KeyEvent.KEYCODE_BACK:

				handleBackKey();

				//				break;
				return true;
				

		}*/

		return super.onKeyDown(keyCode, event);
	}

	protected void handleBackKey()
	{

		/*dialog = new AlertDialog.Builder(this).setMessage(
				R.string.activity_nvchart_backkey_tip).setPositiveButton(
				R.string.activity_nvchart_alert_ok, null).create();
		dialog.show();*/
		
		
		new CustomizeDialog(this, getResources().getString(R.string.info), 
				getResources().getString(R.string.activity_nvchart_backkey_tip), getResources().getString(R.string.ok)).show();

	}

	protected class DownloadUpChartTask extends DownloadChartTask
	{

		private String		dateType;

		private boolean	isTimeout	= false;

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			startSunFlowerAnimation(aview, null);

			if (!isAllTaskExcecuting)
			{

				aview.setIsShowBackground(false);
			}
			showUpView(SUNFLOWER_VIEW);
		}

		protected List doInBackground(String... dateType)
		{

			TDStockLog.d("Print_Info", "===start doInba dateType: " + dateType);

			this.dateType = dateType[0];

			List dataList = null;

			try
			{
				dataList = chartDataHelper.getDataList(dateType[0]);
			}
			catch (SocketTimeoutException e)
			{
				// TODO Auto-generated catch block
				isTimeout = true;

				e.printStackTrace();
			}

			//				//如果没有网络超时，才写入数据,用于调试
			//				if(!isTimeout){
			//					
			//					 TDStockLog.d("Print_Info", "===over doInba dateType: "+dateType);
			//			    	 
			//			    	 if(dataList == null){
			//			    		 
			//			    		 TDStockLog.d("Print_Info", "datalist is null");
			//			    	 }
			//			    	 else{
			//			    		 writeToFile(dataList,dateType[0]);
			//			    	 }
			//				}

			return dataList;
		}

		protected void onPostExecute(List dataList)
		{

			//如果没有网络超时,绘制图表
			if (!isTimeout)
			{

				TDStockLog.d("Print_Info", "===start onPostEx  dateType: "
						+ dateType);

				_aboveView = getUpView(dataList, dateType);

				initUpChartLayout();

				dateList = dataList;

				stopSunFlowerAnimation();

				TDStockLog.d("Print_Info", "===over onPostEx  dateType: "
						+ dateType);

				upSunFlowerContainer.setVisibility(View.INVISIBLE);
			}
			else
			{//如果网络超时,提示“网络超时”

				_aboveView = new UpNoDataView(NvChart.this,
						getString(R.string.activity_nvchart_timeout));

				initUpChartLayout();

				stopSunFlowerAnimation();
			}

		}
	};

	protected class DownloadDownChartTask extends DownloadChartTask
	{

		private String		dateType;

		private boolean	isTimeout	= false;

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			startSunFlowerAnimation(null, dview);

			if (!isAllTaskExcecuting)
			{

				dview.setIsShowBackground(false);
			}

			showDownView(SUNFLOWER_VIEW);
		}

		protected List doInBackground(String... dateType)
		{

			TDStockLog.d("Print_Info", "===start doInba dateType: " + dateType);

			this.dateType = dateType[0];

			List dataList = null;

			try
			{
				dataList = chartDataHelper.getDataList(dateType[0]);
			}
			catch (SocketTimeoutException e)
			{
				// TODO Auto-generated catch block

				isTimeout = true;

				e.printStackTrace();
			}

			//			//如果没有网络超时，才写入数据,用于调试
			//			if(!isTimeout){
			//				
			//				 TDStockLog.d("Print_Info", "===over doInba dateType: "+dateType);
			//		    	 
			//		    	 if(dataList == null){
			//		    		 
			//		    		 TDStockLog.d("Print_Info", "datalist is null");
			//		    	 }
			//		    	 else{
			//		    		 writeToFile(dataList,dateType[0]);
			//		    	 }
			//			}

			return dataList;
		}

		protected void onPostExecute(List dataList)
		{

			//如果没有网络超时,绘制图表
			if (!isTimeout)
			{

				TDStockLog.d("Print_Info", "===start onPostEx  dateType: "
						+ dateType);

				_underView = getDownView(dataList, dateType);

				initDownChartLayout();

				dateList = dataList;

				stopSunFlowerAnimation();

				TDStockLog.d("Print_Info", "===over onPostEx  dateType: "
						+ dateType);

			}
			else
			{//如果网络超时,提示“网络超时”

				_underView = new DownNoDataView(NvChart.this,
						getString(R.string.activity_nvchart_timeout));

				initDownChartLayout();

				stopSunFlowerAnimation();
			}

		}
	};

	protected class DownloadAllChartTask extends DownloadChartTask
	{

		private String		dateType;

		private boolean	isTimeout	= false;

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			isAllTaskExcecuting = true;

			TDStockLog.d("Print_Info", "onPreExecute");
			startSunFlowerAnimation(aview, dview);

			aview.setIsShowBackground(true);

			if (dview != null)
			{

				dview.setIsShowBackground(true);
			}

			showUpAndDownView(SUNFLOWER_VIEW);
		}

		protected List doInBackground(String... dateType)
		{

			TDStockLog.d("Print_Info", "doInBackground");

			this.dateType = dateType[0];

			List dataList = null;
			try
			{
				dataList = chartDataHelper.getDataList(dateType[0]);
			}
			catch (SocketTimeoutException e)
			{
				// TODO Auto-generated catch block

				isTimeout = true;

				e.printStackTrace();

			}

			//			//如果没有网络超时，才写入数据,用于调试
			//			if(!isTimeout){
			//				
			//				 TDStockLog.d("Print_Info", "===over doInba dateType: "+dateType);
			//		    	 
			//		    	 if(dataList == null){
			//		    		 
			//		    		 TDStockLog.d("Print_Info", "datalist is null");
			//		    	 }
			//		    	 else{
			//		    		 writeToFile(dataList,dateType[0]);
			//		    	 }
			//			}

			return dataList;
		}

		protected void onPostExecute(List dataList)
		{

			//如果没有网络超时,绘制图表
			if (!isTimeout)
			{

				TDStockLog.d("Print_Info", "onPostExecute");

				TDStockLog.d("Print_Info", "===start onPostEx  dateType: "
						+ dateType);

				/* _aboveView = getUpView(dataList, dateType);
				 
				 _underView = getDownView(dataList, dateType);*/

				getUpAndDownView(dataList, dateType);

				initChartLayout();

				dateList = dataList;

				stopSunFlowerAnimation();

				TDStockLog.d("Print_Info", "===over onPostEx  dateType: "
						+ dateType);

				isAllTaskExcecuting = false;
			}
			else
			{//如果网络超时,提示“网络超时”

				_aboveView = new UpNoDataView(NvChart.this,
						getString(R.string.activity_nvchart_timeout));

				_underView = new DownNoDataView(NvChart.this,
						getString(R.string.activity_nvchart_timeout));

				initChartLayout();

				stopSunFlowerAnimation();
			}

		}
	};

	// 至少保留一位小数
	protected String getStringPrice(double source)
	{

		int n = 6;

		String s = formatToNChars(source, n);

		if (s.length() < (n - 1) && !s.contains("."))
		{

			s += ".0";

		}

		return s;
	}

	protected String getStringRsi(double source)
	{

		/* String s = formatToNChars(source, 6);
		 
		 if(s.length() < 5 && !s.contains(".")){
			 
			 s += ".0";
			 
		 }*/
		String s = formatToNChars(source, 4); //modified by haibo, 2011-06-23, do not need so many scale.

		if (s.length() < 3 && !s.contains("."))
		{

			s += ".0";

		}

		return s;
	}

	private String formatToNChars(double value, int n)
	{

		String svalue = value + "";

		//长度小于n，直接返回
		if (svalue.length() <= n)
		{

			return svalue;
		}

		String sinteger = Math.round(value) + "";

		//整数长度超过n - 1时，直接返回整数，不会出现“1.”这样的数字
		if (sinteger.length() >= n - 1)
		{

			return sinteger;

		}

		TDStockLog.d("Print_Info", "value: " + value);

		//小数位数
		int digitNum = n - sinteger.length() - 1;

		//		 float temp = (float) Math.pow(10, digitNum);

		double temp = Math.pow(10, digitNum);

		value *= temp;

		TDStockLog.d("Print_Info", "value: " + value);

		String result = Math.round(value) / temp + "";

		TDStockLog.d("Print_Info", "result: " + result);

		return result;
	}

	//上下图表和太阳花切换
	private boolean showUpAndDownView(int i)
	{

		switch (i)
		{
			//显示chart
			case CHART_VIEW:

				downSunFlowerContainer.setVisibility(View.INVISIBLE);

				upSunFlowerContainer.setVisibility(View.INVISIBLE);

				break;
			//显示sunflower
			case SUNFLOWER_VIEW:

				_aboveContainer.setVisibility(View.GONE);
				upSunFlowerContainer.setVisibility(View.VISIBLE);
				_underContainer.setVisibility(View.GONE);
				downSunFlowerContainer.setVisibility(View.VISIBLE);

				break;

		}

		return true;

	}

	//上面的chart上是否显示太阳花
	private boolean showUpView(int i)
	{

		switch (i)
		{
			//显示chart
			case CHART_VIEW:

				_aboveContainer.setVisibility(View.VISIBLE);
				upSunFlowerContainer.setVisibility(View.INVISIBLE);

				break;
			//显示sunflower
			case SUNFLOWER_VIEW:

				upSunFlowerContainer.setVisibility(View.VISIBLE);

				break;

		}

		return true;

	}

	//下面的chart上是否显示太阳花
	private boolean showDownView(int i)
	{

		switch (i)
		{
			//显示chart
			case CHART_VIEW:

				_underContainer.setVisibility(View.VISIBLE);
				downSunFlowerContainer.setVisibility(View.INVISIBLE);

				break;
			//显示sunflower
			case SUNFLOWER_VIEW:

				downSunFlowerContainer.setVisibility(View.VISIBLE);

				break;

		}

		return true;

	}

	@Override
	protected void onStart()
	{
		super.onStart();
		this.initView(getDateType());
	}

	protected abstract void getUpAndDownView(List dataList, String dateType);

	@Override
	protected void onDestroy()
	{
		super.onDestroy();

		if (upTask != null && upTask.getStatus() != Status.FINISHED)
		{

			upTask.cancel(true);

			boolean b = upTask.isCancelled();

			TDStockLog.d("Print_Info", "====upTask=======" + b);
		}

		if (downTask != null && downTask.getStatus() != Status.FINISHED)
		{

			downTask.cancel(true);

			boolean b = downTask.isCancelled();

			TDStockLog.d("Print_Info", "====upTask=======" + b);
		}

		if (allTask != null && allTask.getStatus() != Status.FINISHED)
		{

			allTask.cancel(true);

			boolean b = allTask.isCancelled();

			TDStockLog.d("Print_Info", "====upTask=======" + b);
		}

	}

	protected boolean isEqual(double d1, double d2)
	{

		return Math.abs(d1 - d2) < 0.000001;
	}

	protected String getActivationCode()
	{

		SharedPreferences _prefsActivationCode = getSharedPreferences(
				CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);;
		String result = _prefsActivationCode.getString(
				CommonDefn.PREFERENCE_TRIAL_ACTIVE_CODE, "");
		return result;
	}

	@Override
	protected void onPause()
	{
		super.onPause();

		this.stopSunFlowerAnimation();
	}

//	@Override
	protected void forwardToLastActivity()
	{

		this.cacelDialog();

		TDStockLog.d("Print_Info", "====forwardToLastActivity=======");
	    this.onBackPressed();
		
		
	  /*  Intent  i = new Intent();
		i.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_CLEAR_TOP); 
		//SwitchFreeActivity(RealtimeStockActivity.class, i);
		
		appHost.actListController.ActivityForwardSwitch(this, RealtimeStockActivity.class, i);*/
		
		/*Intent intent = null;
		if (TextUtils.isDigitsOnly(theItemCode))
		{
			intent =new Intent(getApplicationContext(),CurrentStockInfoActivity.class);

			intent = new Intent(getApplicationContext(),
					CurrentStockInfoActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			View viewIntent = StockGroup.group.getLocalActivityManager()
					.startActivity(
							CurrentStockInfoActivity.class
									.getSimpleName(), intent)
					.getDecorView();
			StockGroup.group.setContentView(viewIntent); // modify by ouyangzhihui 2011-05-16
			 		
			
			
		}
		else if (ForeignExchangeInfo.CODE_TO_NAME.containsKey(theItemCode))
		{
			intent =new Intent(getApplicationContext(),ForeignExchangeActivity.class);

			intent = new Intent(getApplicationContext(),
					ForeignExchangeActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			View viewIntent = ForeignExchangeGroup.group
					.getLocalActivityManager().startActivity(
							ForeignExchangeActivity.class
									.getSimpleName(), intent)
					.getDecorView();
			ForeignExchangeGroup.group.setContentView(viewIntent); // modify by ouyangzhihui 2011-05-16
	
		}
		else
		{
			intent =new Intent(getApplicationContext(),IndexActivity.class);

			intent = new Intent(getApplicationContext(), IndexActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			View viewIntent = IndexGroup.group.getLocalActivityManager()
					.startActivity(IndexActivity.class.getSimpleName(),
							intent).getDecorView();
			IndexGroup.group.setContentView(viewIntent); // modify by ouyangzhihui 2011-05-16
		
	
		}

		//intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		//		NvChart.this.setResult(RESULT_OK, getIntent());

		startActivity(intent);*/


	}

	private void cacelDialog()
	{

		if (dialog != null)
		{

			dialog.cancel();

		}

	}
	
	
	protected synchronized void handleExitApplication()
	{
		new AlertDialog.Builder(this).setTitle(
				getResources().getString(R.string.info)).setMessage(
				getResources().getString(R.string.application_exit_tips))
				.setIcon(
						getResources().getDrawable(
								R.drawable.help_menu_icon))
				.setPositiveButton(getResources().getString(R.string.ok),
						new DialogInterface.OnClickListener()
						{
							public void onClick(
									DialogInterface dialoginterface,
									int i)
							{
								((ITDLApplication) getApplicationContext())
										.setExitApp(true);
								exitApp();
							}
						}).setNegativeButton(
						getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,
									int whichButton)
							{
							}
						}).show();
	}

	public void exitApp()
	{
		finish();
		/*Process.killProcess(Process.myPid());*/
		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);
	}

	protected synchronized void genLauncher()
	{
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		//intent2.setComponent(new ComponentName(this.getPackageName(),    ".activity.LoginActivity"));    
		intent2.setComponent(new ComponentName(this.getPackageName(),
				".activity.SplashActivity"));

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(this,
						R.drawable.icon));
		sendBroadcast(shortcutIntent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		menu.add(0, CREATE_LAUNCHER, 0, _menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP, 1, _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext())
						.setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		_menu_exit_app_res = getResources().getString(R.string.app_exit);
		_menu_gen_launcher_res = getResources().getString(
				R.string.app_launcher);
		super.onCreate(savedInstanceState);
	}

	//** Rotate back to normal
	public void ScreenOrientation_Response(SCR_ORIENTATION orientation)
	{
		if (orientation == SCR_ORIENTATION.PORTRAIT)
		{
			TDStockLog.d("Print_Info", "called by sensor ");
			forwardToLastActivity();			
		}						
	}	
	
	

}
